package com.mall.common.domain.manage;

import static com.mall.common.Constants.USER_IS_CORP_MANAGER;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OrderBy;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.mall.common.bean.User;
import com.mall.common.domain.BaseEntity;
import com.mall.common.util.PropertiesHelper;

/**
 * 用户实体类  @author zhenglong
 */
@Entity
@Table(name="s_user")
public class S_userDomain extends BaseEntity implements UserDetails {

	private static final long serialVersionUID = -3224845335788125657L;

	private String real_name;/** 员工名 **/
	private String username;//登陆账号
	private String password;//密码
	private Boolean isAccountEnabled;//是否禁止账号登陆
	private String loginid; //上次登录的sessionId
	private Integer loginCount; //登录的次数
	private Date lastLoginTime; //上次登录时间
	private String lastLoginIp; //上次登录的IP
	private Date lockedDate;// 账号锁定日期
	private Integer loginFailureCount;//登录失败次数
	private Boolean isAccountLocked;// 账号是否锁定
	private Boolean isAccountExpired;// 账号是否过期
	private Boolean isCredentialsExpired;// 凭证是否过期
	//是否企业管理员Y: 是 N:不是。系统管理员新增的用户默认是企业管理员
	@JsonIgnore private Boolean is_corp_manager;
	@JsonIgnore private Set<Role> roleSet; // 角色
	@JsonIgnore private Collection<GrantedAuthority> authorities;// 角色信息
	@JsonIgnore private S_deptDomain dept;//所属部门
	
	@Transient
	public User getUser(){
		return new User(getId(), username, password, isAccountNonExpired(), 
				isAccountNonLocked(), isCredentialsNonExpired(), isEnabled(), 
				authorities, isSystemManager(), getRoleListIds(), getRoleValues());
	}

	@Transient
	@JsonIgnore
	public String getRoleNames(){
		Set<Role> roles = this.getRoleSet();
		StringBuffer sb = new StringBuffer();
		if(roles != null && roles.size() > 0){
			for(Role role : roles){
				sb.append(role.getName());
			}
			return sb.toString();
		}
		return null;
	}
	
	@Transient
	@JsonIgnore
	public List<Long> getRoleListIds(){
		Set<Role> roles = this.getRoleSet();
		if(roles != null && roles.size() > 0){
			List<Long> roleIds = new ArrayList<Long>(roles.size());
			for(Role role : roles){
				roleIds.add(role.getId());
			}
			return roleIds;
		}
		return null;
	}
	
	@Transient
	@JsonIgnore
	public List<String> getRoleValues(){
		Set<Role> roles = this.getRoleSet();
		List<String> list = new ArrayList<String>();
		if(roles != null && roles.size() > 0){
			for(Role role : roles){
				list.add(role.getValue());
			}
		}
		return list;
	}
	
	@Transient
	public String getName(){
		return username;
	}
	
	/**
	 * 是否系统管理员 
	 * @return
	 */
	@Transient
	@JsonIgnore
	public boolean isSystemManager(){
		//增加系统管理员的权限
		String system_manager_user = PropertiesHelper.getPropertiesValue("config", "system_manager_user");
		List<String> system_manager_users = Arrays.asList(system_manager_user.split(","));
	    return system_manager_users.contains(this.getUsername());
	}

	/**
	 * 是否企业管理员 
	 * @return
	 */
	@Transient
	public boolean isCorpManager(){
		//如果是系统管理员，则"Y"
	    if(USER_IS_CORP_MANAGER.equals(this.getIs_corp_manager())){
	        return true;
	    }
	    return false;
	}

	public String getLoginid() {
		return loginid;
	}

	public void setLoginid(String loginid) {
		this.loginid = loginid;
	}

	@Column(nullable=false,name="isAccountEnabled")
	public Boolean getIsAccountEnabled() {
		return isAccountEnabled;
	}

	public void setIsAccountEnabled(Boolean isAccountEnabled) {
		this.isAccountEnabled = isAccountEnabled;
	}

	@Column(nullable = false,name="isAccountExpired")
	public Boolean getIsAccountExpired() {
		return isAccountExpired;
	}

	public void setIsAccountExpired(Boolean isAccountExpired) {
		this.isAccountExpired = isAccountExpired;
	}

	@Column(length=32)
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@ManyToMany(fetch = FetchType.LAZY)
	@JoinTable(name="s_user_role",joinColumns={@JoinColumn(name="user_id")},
			inverseJoinColumns={@JoinColumn(name="role_id")})
	@OrderBy("name asc")
	public Set<Role> getRoleSet(){
		return roleSet;
	}
	
	public void setRoleSet(Set<Role> roleSet) {
		this.roleSet = roleSet;
	}

	@Column(nullable = false, length=1)
	public Boolean getIs_corp_manager() {
		return is_corp_manager;
	}

	public void setIs_corp_manager(Boolean is_corp_manager) {
		this.is_corp_manager = is_corp_manager;
	}

	@Column(name="loginCount")
	public Integer getLoginCount() {
		return loginCount;
	}

	public void setLoginCount(Integer loginCount) {
		this.loginCount = loginCount;
	}

	@Column(name="lastLoginTime")
	public Date getLastLoginTime() {
		return lastLoginTime;
	}

	public void setLastLoginTime(Date lastLoginTime) {
		this.lastLoginTime = lastLoginTime;
	}

	public String getReal_name() {
		return real_name;
	}

	public void setReal_name(String real_name) {
		this.real_name = real_name;
	}

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "dept_id")
	public S_deptDomain getDept() {
		return dept;
	}

	public void setDept(S_deptDomain dept) {
		this.dept = dept;
	}

	@Column(name="lastLoginIp")
	public String getLastLoginIp() {
		return lastLoginIp;
	}

	public void setLastLoginIp(String lastLoginIp) {
		this.lastLoginIp = lastLoginIp;
	}

	@Column(nullable = false,name="loginFailureCount")
	public Integer getLoginFailureCount() {
		return loginFailureCount;
	}

	public void setLoginFailureCount(Integer loginFailureCount) {
		this.loginFailureCount = loginFailureCount;
	}

	@Column(name="lockedDate")
	public Date getLockedDate() {
		return lockedDate;
	}

	public void setLockedDate(Date lockedDate) {
		this.lockedDate = lockedDate;
	}
	
	@Column(nullable = false,name="isCredentialsExpired")
	public Boolean getIsCredentialsExpired() {
		return isCredentialsExpired;
	}

	public void setIsCredentialsExpired(Boolean isCredentialsExpired) {
		this.isCredentialsExpired = isCredentialsExpired;
	}

	@Transient
	public boolean isAccountNonLocked() {
		return !this.isAccountLocked;
	}
	
	@Column(nullable = false,name="isAccountLocked")
	public Boolean getIsAccountLocked() {
		return isAccountLocked;
	}

	public void setIsAccountLocked(Boolean isAccountLocked) {
		this.isAccountLocked = isAccountLocked;
	}

	@Column(updatable = false, nullable = false, unique = true)
	public String getUsername() {
		return this.username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	@Transient
	public boolean isAccountNonExpired() {
		return !this.isAccountLocked;
	}

	@Transient
	@JsonIgnore
	public boolean isCredentialsNonExpired() {
		return !this.isCredentialsExpired;
	}

	@Transient
	@JsonIgnore
	public boolean isEnabled() {
		return this.isAccountEnabled;
	}
	
	@Override
	@Transient
	@JsonIgnore
	public Collection<GrantedAuthority> getAuthorities() {
		return authorities;
	}

	public void setAuthorities(Collection<GrantedAuthority> authorities) {
		this.authorities = authorities;
	}

	@PrePersist
	public void prePersist(){
		if(is_corp_manager == null){
			is_corp_manager = false;
		}
		
		if(loginFailureCount == null){
			loginFailureCount = 0;
		}
		
		if(isAccountExpired == null){
			isAccountExpired = false;
		}
		
		if(isCredentialsExpired == null){
			isCredentialsExpired = false;
		}
		
		if(isAccountLocked == null){
			isAccountLocked = false;
		}
	}
}
